<?php


namespace App\Http\Middleware;

use App\Models\Token;
use Closure;
use App\Http\Controllers\BaseController;
use Illuminate\Support\Facades\Cache;

class UserAuth extends BaseController
{
    public function handle($request, Closure $next)
    {
        $token = $request->header('auth');

        if (empty($token)){
            return $this->returnJson([], self::WRONG, 'unauthenticated', 'Missingtoken');
        }

        $userInfo = Token::where('token', $token)
            ->where('is_admin', 0)
            ->with(['user'])
            ->first();

        if (empty($userInfo)) {
            return $this->returnJson([], self::WRONG, 'unauthenticated', 'Invalid token');
        }

        if (!empty($userInfo->user->reason)){
            return $this->returnJson([
                "reason" => $userInfo->user->reason,
            ], self::BAND, 'blocked', 'User blocked');
        }

        $request->user = $userInfo;
        return $next($request);
    }
}
